package com.matrix.cantordemo.userbusiness.controller;

import cn.hutool.core.util.ObjectUtil;
import com.cantor.cantorspringbootstarter.anno.CantorReference;
import com.cantor.common.tool.TimeCounter;
import com.matrix.cantordemo.api.entity.Sku;
import com.matrix.cantordemo.api.service.ProductRpcService;
import com.matrix.cantordemo.api.service.UserService;
import com.matrix.cantordemo.common.entity.GlobalResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @CantorReference
    ProductRpcService productRpcService;

    @GetMapping("/userProduct")
    GlobalResponse<List<Sku>> userProduct() {
        long startTime = System.currentTimeMillis();
        return GlobalResponse.ok(productRpcService.userProducts())
                .setTime(System.currentTimeMillis() - startTime);
    }

    @GetMapping("/singleCall")
    GlobalResponse<Long> singleCall() {
        long startTime = System.currentTimeMillis();
        TimeCounter.timeMap.put("focus",startTime);
        productRpcService.singleCall("Message");
        long duration = System.currentTimeMillis() - startTime;
        return GlobalResponse.ok(duration).setTime(duration);
    }

    @GetMapping("/multipleCall")
    GlobalResponse<Long> multipleCall(Integer times) throws InterruptedException {
        long startTime = System.currentTimeMillis();

        final int nThreads = ObjectUtil.isNull(times) ? 30 : times;
        final CountDownLatch latch = new CountDownLatch(nThreads);
        final List<Long> timeList = new LinkedList<>();
        for (int i = 0; i < nThreads; i++) {
            new Thread(() -> {
                long start = System.currentTimeMillis();
                productRpcService.singleCall("Message");
                timeList.add(System.currentTimeMillis() - start);
                latch.countDown();
            }).start();
        }
        latch.await();
        long duration = System.currentTimeMillis() - startTime;
        return GlobalResponse.ok(timeList).setTime(duration);
    }


}
